import redis
from redis import ConnectionPool
from typing import Dict, Optional
import logging
from config import REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_MAX_CONNECTIONS, REDIS_SOCKET_TIMEOUT

logger = logging.getLogger(__name__)


class RedisClientManager:
    """
    Redis客户端管理器，统一管理多个数据库连接
    """
    _clients: Dict[int, redis.Redis] = {}
    _pools: Dict[int, ConnectionPool] = {}
    
    @classmethod
    def _create_pool(cls, db: int) -> ConnectionPool:
        """创建Redis连接池"""
        return ConnectionPool(
            host=REDIS_HOST,
            port=REDIS_PORT,
            password=REDIS_PASSWORD,
            db=db,
            max_connections=REDIS_MAX_CONNECTIONS,
            socket_timeout=REDIS_SOCKET_TIMEOUT,
            retry_on_timeout=True,
            health_check_interval=30
        )
    
    @classmethod
    def get_client(cls, db: int) -> redis.Redis:
        """获取指定数据库的Redis客户端"""
        if db not in cls._clients:
            logger.info(f"Creating Redis client for database {db}")
            cls._pools[db] = cls._create_pool(db)
            cls._clients[db] = redis.Redis(connection_pool=cls._pools[db])
        return cls._clients[db]
    
    @classmethod
    def close_all(cls):
        """关闭所有连接"""
        for db, client in cls._clients.items():
            logger.info(f"Closing Redis client for database {db}")
            client.close()
        cls._clients.clear()
        cls._pools.clear()


# 向后兼容的全局变量
r = RedisClientManager.get_client(3)
r2 = RedisClientManager.get_client(2)

# 便捷函数
def get_redis_client(db: int = 3) -> redis.Redis:
    """获取Redis客户端的便捷函数"""
    return RedisClientManager.get_client(db)